package com.hzw.saas.web.app.workspace.aspect;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hzw.saas.common.config.util.AssertUtil;
import com.hzw.saas.common.security.utils.SecurityUtils;
import com.hzw.saas.common.util.SpringELUtils;
import com.hzw.saas.service.workspace.mapper.WorkInstanceMapper;
import com.hzw.saas.service.workspace.pojo.model.WorkInstance;
import com.hzw.saas.web.app.workspace.annotation.WorkspaceOperation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 控制权限
 * </p>
 *
 * @author sonam
 * @since 2020-12-23
 */
@Aspect
@Component
@Slf4j
@AllArgsConstructor
public class WorkInstanceAspect {

    private final WorkInstanceMapper workInstanceMapper;

    @SneakyThrows
    @Before("@annotation(workspaceOperation)")
    public void memberBefore(JoinPoint joinPoint, WorkspaceOperation workspaceOperation) {
        String instId = SpringELUtils.getSpelValue(joinPoint, workspaceOperation.instId(), String.class);
        AssertUtil.assertThrow("你没有权限操作该实例", HttpStatus.FORBIDDEN,
            workInstanceMapper.selectCount(Wrappers.<WorkInstance>lambdaQuery()
            .eq(WorkInstance::getUserId, SecurityUtils.getUser().getUserId())
            .eq(WorkInstance::getInstId, instId)) == 0);
    }

}
